<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-09-23 08:48
 *
 * 项目：rm  -  $  - baiduPayment.php
 *
 * 作者：liwei 
 */

namespace modules\levpays\modules\baidupay\sdk;

use Lev;
use lev\helpers\cacheFileHelpers;
use lev\helpers\curlHelper;
use modules\levpays\levpaysHelper;
use modules\levpays\modules\baidupay\helpers\baidupaySetHelper;
use modules\levpays\modules\baidupay\sdk\sdk\paySdk;

!defined('INLEV') && exit('Access Denied LEV');

class baiduPayment extends paySdk
{

    public static $instance = null, $config = null;

    public static function loadConfig() {
        if (isset(static::$config)) return static::$config;

        static::$config = [
            //智能小程序的 App Key，可在「开发者平台 - 设置 - 开发设置」页中获得。（要先在开发者平台创建小程序）
            'appid'       => Lev::stget('appid', 'baidupay'),
            //智能小程序的 App Secret，请妥善保存，如丢失可在「开发者平台 - 设置 - 开发设置」页面重置后获得，重置后 App Secret 将会被更新。
            'appsecret'   => Lev::stget('appsecret', 'baidupay'),

            'deal_id'     => Lev::stget('deal_id', 'baidupay'), // 百度收银台的财务结算凭证

            'app_key'     => Lev::stget('app_key', 'baidupay'), // 表示应用身份的唯一ID

            //私钥生成文档： https://smartprogram.baidu.com/docs/develop/function/keygen_v2/
            'private_key' => Lev::stget('private_key', 'baidupay'), // 私钥原始字符串 必须转pcs8

            'public_key'  => Lev::stget('public_key', 'baidupay'), // 平台公钥

            'notify_url'  => Lev::stget('notify_url', 'baidupay') ?: Lev::$aliases['@siteurl'].'/baidu_pay_notify.php', // 支付回调地址

        ];
        (empty(static::$config['deal_id']) || empty(static::$config['public_key'])) &&
        is_file($file = __DIR__ . '/.baidu.config.php') &&
        static::$config = include $file;
        return static::$config;
    }

    /**
     * 文档： https://smartprogram.baidu.com/docs/develop/serverapi/power_exp/
     * @param $code
     */
    public static function getAccessToken()
    {
        static::loadConfig();

        $cacheKey = 'baiduPaymentAccessToken/123';
        $result = cacheFileHelpers::getc($cacheKey);
        if (!empty($result['access_token']) && baidupaySetHelper::cachePayToken()) {
            return $result['access_token'];
        }

        $pm['url'] = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id='.static::$config['appid'].'&client_secret='.static::$config['appsecret'].'&scope=smartapp_snsapi_base';
        $pm['httpheader'] = array("Content-type:application/x-www-form-urlencoded");
        $result = curlHelper::doCurl($pm);//echo $result;
        $result = json_decode($result, true);//print_r($result);
        !empty($result['access_token']) && cacheFileHelpers::setc($cacheKey, $result, Lev::$app['timestamp'] + $result['expires_in'] - 3600);
        //file_put_contents(__DIR__ .'/log.txt', $code.print_r($result, true), FILE_APPEND);

        static::$config['_result'] = $result;

        return $result['access_token'];
    }

    /**
     * 文档： https://smartprogram.baidu.com/docs/develop/function/tune_up_queryorderdetail_2.0/
     * @param string $tradeNo  T0000000000000000215
     * @param string $alipayTradeNo
     * @return bool|mixed
     *
     * XHRGEThttp://127.0.0.1/dz/34/rm/levs.php?r=pay/check-trade-no&paytypeid=2&id=levpays&pre=BDUPC&tradeNo=T0000000000000000040&userck=undefined&_csrf=34db76ab&_=0.32449936715108796
    [HTTP/1.1 200 OK 807ms]

    1

    {"0":{"errno":0,"msg":"success","data":{"orderId":87048436728447,"userId":3356406266,"dealId":42378000,"status":2,"subStatus":20,"type":273644,"settlePrice":100,"oriPrice":100,"payMoney":100,"count":1,"tradeNo":"2109240378928700","totalMoney":100,"tpId":33008,"tpOrderId":"T0000000000000000215","createTime":1632478486,"parentOrderId":-1,"parentType":1,"payType":1124,"bizInfo":"{\"tpData\":{\"appKey\":\"MMUcwh\",\"dealId\":\"2735086681\",\"tpOrderId\":\"T0000000000000000215\",\"rsaSign\":\"AsytJsYZIxdkJhmAq4Csf+gjXP15cvIH8nqqYPKRSdTDES5wBxsHQaMxyE+sRU147NmNl\/wgcT7JH6T9URDgGdRef\/hki34MJZur8OyvvFLNsAlhwKKdoRVVEU8ctSsy8jJMlrVTRI0usnk+1ECsUdqbAPCY7nlFlEe5XKhCP2s=\",\"totalAmount\":100,\"returnData\":\"\",\"displayData\":{\"cashierTopBlock\":[[{\"leftCol\":\"7\u5929\",\"rightCol\":\"\u8d85\u503cVIP7\u5929\u5361\"},{\"leftCol\":\"\u6570\u91cf\",\"rightCol\":1},{\"leftCol\":\"\u8ba2\u5355\u91d1\u989d\",\"rightCol\":100}],[{\"leftCol\":\"\u670d\u52a1\u5730\u5740\",\"rightCol\":\"-\"},{\"leftCol\":\"\u670d\u52a1\u65f6\u95f4\",\"rightCol\":\"2021\/09\/24 18:14\"},{\"leftCol\":\"\u670d\u52a1\u4eba\u5458\",\"rightCol\":\"\u5e2e\u5e2e\u5e2e\u7f51\"}]]},\"dealTitle\":\"7\u5929\",\"dealSubTitle\":\"\u8d85\u503cVIP7\u5929\u5361\",\"dealThumbView\":\"https:\/\/b.bdstatic.com\/searchbox\/icms\/searchbox\/img\/swan-logo.png\"},\"orderDetailData\":\"\",\"cuid\":\"5900D5F705D1EC7427E6F56206981308|VDGQUGLGP\",\"appId\":\"qeZ7IXyvaP9TV9VuvtqtI4ZyMraT9AVv_localDebug\",\"nativeAppId\":\"baiduboxapp\",\"platformId\":\"100003\",\"isAccountDataFlow\":1,\"isFoldChannel\":1}","openId":"50zRWF3-rpq5EMmBx94KteDKd1","appKey":"qeZ7IXyvaP9TV9VuvtqtI4ZyMraT9AVv","appId":24881689},"traceId":"f2d9bc60-2010-4c82-b96c-32e50c9ea3aa","_paySuccess":false},"error":{"message":"-"},"message":"-","status":-2}


     */
    public static function checkTradeNo($tradeNo, $alipayTradeNo = '') {
        //$tradeNo = 'T0000000000000000210';

        if ($tradeNo || $alipayTradeNo){
            static::loadConfig();
            $pm['url'] = 'https://openapi.baidu.com/rest/2.0/smartapp/pay/paymentservice/findByTpOrderId';
            $pm['url'].= '?tpOrderId='.$tradeNo.'&pmAppKey='.static::$config['app_key'].'&access_token='.static::getAccessToken();
            $json = curlHelper::doCurl($pm);
            $result = json_decode($json, true);
            $result['_paySuccess'] =  empty($result['errno']) && $result['data']['status'] == 2;
            return $result;
        }
        return false;
    }

    public static function paySuccess(array $msg, $tradeNo, $pre, array $outTradeInfo)
    {
        static::loadConfig();
        static::$config['openidField'] = 'baiduopenid';
        static::$config['paytypeid']   = 2;
        //static::$config['appid']       = $outTradeInfo['data']['appKey'];//static::$config['appid'];
        //static::$config['mchid'] = static::$config['mchid'];

        $outTradeInfo['openid']         = $outTradeInfo['data']['openId'];
        $outTradeInfo['transaction_id'] = $outTradeInfo['data']['tradeNo'];
        $outTradeInfo['appid']          = $outTradeInfo['data']['appKey'];
        $outTradeInfo['mchid']          = '';
        $outTradeInfo['success_time']   = $outTradeInfo['data']['createTime'];

        levpaysHelper::paySuccess($msg, $tradeNo, $pre, $outTradeInfo, static::$config);
    }
}